<template>
  <div class="account">
    <el-form
      ref="loginFormRef"
      :model="loginFormData"
      :rules="loginFormRules"
      @keyup.enter="handleLogin"
    >
      <el-form-item prop="username">
        <el-input
          v-model.trim="loginFormData.username"
          placeholder="用户名"
          type="text"
          tabindex="1"
          :prefix-icon="User"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model.trim="loginFormData.password"
          placeholder="密码"
          type="password"
          tabindex="2"
          :prefix-icon="Lock"
          size="large"
          show-password
          @blur="() => handleBlur()"
          @focus="() => handleFocus()"
        />
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model.trim="loginFormData.code"
          placeholder="验证码"
          type="text"
          tabindex="3"
          :prefix-icon="Key"
          maxlength="7"
          size="large"
          @blur="() => handleBlur()"
          @focus="() => handleFocus()"
        >
          <template #append>
            <el-image
              :src="codeUrl"
              draggable="false"
              @click="createCode"
            >
              <template #placeholder>
                <el-icon>
                  <Picture />
                </el-icon>
              </template>
              <template #error>
                <el-icon>
                  <Loading />
                </el-icon>
              </template>
            </el-image>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type {
  LoginRequestData,
  LoginResponseData,
  CaptchaResponseData
} from '@/types/login.d'
import { ElMessage } from 'element-plus'
import { Key, Loading, Lock, Picture, User } from '@element-plus/icons-vue'
import { accountLogin, getCaptchaApi } from '@/services/user'
import { useUserStore } from '@/pinia/stores/user'
import { sessionCache } from '@/utils/cache/cookies'
import { CacheKey } from '@/utils/constants/cache-key'

const props = defineProps({
  handleBlur: {
    type: Function,
    required: true
  },
  handleFocus: {
    type: Function,
    required: true
  },
  updateLoading: {
    type: Function,
    required: true
  }
})
const redirect = ref('')
const router = useRouter()
const route = useRoute()

/** 登录表单Form的引用 */
const loginFormRef = ref<FormInstance | null>(null)

/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  username: sessionCache.getCache(CacheKey.USERNAME) ?? '',
  password: sessionCache.getCache(CacheKey.PASSWORD) ?? '',
  code: ''
})
/** 验证码图片 URL */
const codeUrl = ref('')

/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const userStore = useUserStore()
watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query.redirect || ''
  },
  { immediate: true }
)
/** 登录 */
function handleLogin(isRemember: boolean) {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error('表单校验不通过')
      return
    }
    props.updateLoading(true)
    accountLogin({
      ...loginFormData
    })
      .then(({ data }: LoginResponseData) => {
        console.log(data, redirect.value)
        userStore.setToken(data.token)
        userStore.userId = data.id

        rememberAccount(isRemember)

        redirectPage()
      })
      .catch((error) => {
        createCode()
        loginFormData.password = ''
        console.log(error)
      })
      .finally(() => {
        props.updateLoading(false)
      })
  })
}

/** 是否记住用户密码 */
function rememberAccount(isRemember: boolean) {
  if (isRemember) {
    sessionCache.setCache(CacheKey.USERNAME, loginFormData.username)
    sessionCache.setCache(CacheKey.PASSWORD, loginFormData.password)
  } else {
    sessionCache.removeCache(CacheKey.USERNAME)
    sessionCache.removeCache(CacheKey.PASSWORD)
  }
}
/** 登录成功是否需要重定向 */
function redirectPage() {
  if (redirect.value) router.push({ path: route.query.redirect })
  else router.push('/')
}
/** 创建验证码 */
function createCode() {
  // 清空已输入的验证码
  loginFormData.code = ''
  // 清空验证图片
  codeUrl.value = ''
  // 获取验证码图片
  getCaptchaApi().then(({ data }: CaptchaResponseData) => {
    codeUrl.value = data.captcha
  })
}

// 初始化验证码
createCode()

defineExpose({ handleLogin })
</script>
